from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.responses import JSONResponse
from app.models import responses


# 定义中间件
def fixPathMiddleware(request: Request, call_next):
    """
    中间件：修复路径端点
    行为 1: 移除路径长度大于 1 的末端的反斜杠, 其他情况保持不变

    例如：/api/v1/login/ 这种情况将被调整为 /api/v1/login
    """
    raw_path = request.scope.get('path', '')
    if len(raw_path) > 1 and raw_path.endswith('/'):
        path = raw_path[:-1]
    else:
        path = raw_path
    request.scope['path'] = path
    response = call_next(request)
    return response


# 中间件列表
middlewares = [fixPathMiddleware]


def register_middlewares(app: FastAPI):
    """注册中间件 """
    for middleware in middlewares:
        app.middleware('http')(middleware)

    return len(middlewares)


def register_exc_handler(app: FastAPI):
    @app.exception_handler(405)
    async def handle_405(_request: Request, _exc: HTTPException):
        return JSONResponse(
            content=responses.Response10005().model_dump(),
            status_code=200
        )

    @app.exception_handler(RequestValidationError)
    async def handle_RequestValidationError(_request: Request, _exc: RequestValidationError):
        print(_exc.errors())
        return JSONResponse(
            content=responses.Response10001().model_dump(),
            status_code=200
        )

    @app.exception_handler(500)
    async def handle_500(_request: Request, exc: Exception):
        if app.settings.is_dev:
            data = {
                'error': str(exc)
            }
        else:
            data = None
        return JSONResponse(
            content=responses.Response10006(data=data).model_dump(),
            status_code=200
        )

    @app.exception_handler(404)
    async def handle_404(_request: Request, _exc: Exception):
        return JSONResponse(
            content=responses.Response10007().model_dump(),
            status_code=200
        )

    @app.exception_handler(responses.FailureResponseError)
    async def handle_FailureResponseError(_request: Request, exc: responses.FailureResponseError):
        return JSONResponse(
            content=exc.response().model_dump(),
            status_code=200
        )
